/*
 * Copyright 2008 Andrej Herich
 * 
 * http://azetclient.yw.sk/
 * http://azetclient.googlecode.com/
 * 
 * This file is part of AzetClient.
 * 
 * AzetClient is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * AzetClient is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with AzetClient.  If not, see <http://www.gnu.org/licenses/>.
 */

package sk.yw.azetclient;

import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;

/**
 *
 * @author error216
 */
public class AzetCookieStore implements CookieStore {
    
    private static final Logger logger = Logger.getLogger(AzetCookieStore.class);
    
    private Map<URI, List<HttpCookie>> store
            = Collections.synchronizedMap(new HashMap<URI, List<HttpCookie>>());

    public synchronized void add(URI uri, HttpCookie cookie) {
        // logger.debug("add(" + uri + ", " + cookie + ")");
        List<HttpCookie> cookies = store.get(uri);
        
        if (cookies == null) {
            cookies = Collections.synchronizedList(new ArrayList<HttpCookie>());
            store.put(uri, cookies);
        }

        if (!cookies.add(cookie))
            logger.warn("Unable to add cookie");
    }

    public List<HttpCookie> get(URI uri) {
        // logger.debug("get(" + uri + ")");
        List<HttpCookie> cookies = store.get(uri);
        
        if (cookies == null) {
            cookies = Collections.synchronizedList(new ArrayList<HttpCookie>());
            store.put(uri, cookies);
        }
        
        return Collections.unmodifiableList(cookies);
    }

    public List<HttpCookie> getCookies() {
        // logger.debug("getCookies()");
        List<HttpCookie> allCookies = new ArrayList<HttpCookie>();
        
        for (List<HttpCookie> cookies : store.values()) {
            allCookies.addAll(cookies);
        }
        
        return allCookies;
    }

    public List<URI> getURIs() {
        // logger.debug("getURIs()");
        return new ArrayList<URI>(store.keySet());
    }

    public boolean remove(URI uri, HttpCookie cookie) {
        // logger.debug("remove(" + uri + ", " + cookie + ")");
        return store.get(uri).remove(cookie);
    }

    public boolean removeAll() {
        // logger.debug("removeAll()");
        store.clear();
        return true;
    }
    
}
